import com.alibaba.fastjson.JSONObject;
import entity.ResponseData;
import utils.Base64Util;
import utils.FallDetectionUtils;
import utils.FileUtil;
import utils.HttpUtil;

import java.net.URLEncoder;

/**
 * 人体关键点识别
 */
public class BodyAnalysis {
    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String body_analysis() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_analysis";
        try {
            // 本地文件路径
            String filePath = "test/test_20.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.9eeb2842c1d2c6000e48c524aae4922e.2592000.1629264825.282335-24569897";

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        //  获得JSON字符串
        String s = BodyAnalysis.body_analysis();
        //  将JSON字符串序转换成对象
        ResponseData responseData = JSONObject.parseObject(s, ResponseData.class);
        //  拿到相应坐标
        double top_head_x = responseData.getPersonInfo()[0].getBodyParts().getTop_head().getX();
        double top_head_y = -responseData.getPersonInfo()[0].getBodyParts().getTop_head().getY();
        double left_ankle_x = responseData.getPersonInfo()[0].getBodyParts().getLeft_ankle().getX();
        double left_ankle_y = -responseData.getPersonInfo()[0].getBodyParts().getLeft_ankle().getY();
        double right_ankle_x = responseData.getPersonInfo()[0].getBodyParts().getRight_ankle().getX();
        double right_ankle_y = -responseData.getPersonInfo()[0].getBodyParts().getRight_ankle().getY();
        boolean isFall = FallDetectionUtils.isFall(top_head_x, top_head_y, left_ankle_x, left_ankle_y, right_ankle_x, right_ankle_y);
        if (isFall == true){
            System.out.println("摔倒了！！");
        }else {
            System.out.println("没有摔倒！！");
        }

    }
}
